package vista;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import modelo.Modelo;
import modelo.funciones.Funcion;

public class VistaGraficador extends JPanel implements ListSelectionListener {
	
	private Modelo modelo;
	private List<Funcion> funciones;
	
	public VistaGraficador(Modelo modelo){
		this.setModelo(modelo);
		this.setFunciones(new ArrayList<Funcion>());
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g) ;
		int centroX=(this.getSize().width)/2;
		int centroY=(this.getSize().height)/2;
		g.setColor(Color.BLACK);
		g.drawLine(0,centroY,centroX*2,centroY);
		g.drawLine(centroX,0,centroX,centroY*2);
		if (!this.getModelo().getFunciones().isEmpty()){
		for (int j=0;j<this.getFunciones().size();j++){
		int[] vector=new int[centroX*2];
		for (int i=-centroX;i<centroX;i++){
			try {
			vector[i+centroX]=(int)this.getFunciones().get(j).evaluar(i);
			} catch (RuntimeException e){
				vector[i+centroX]=-this.getSize().height;
			}
		}
		g.setColor(new Color(j*j*400+j*19000+29000));
		for (int i=0;i<centroX*2;i++)
			g.drawLine(i,-vector[i]+centroY,i,-vector[i]+centroY);
		}}
	}

	public void setFunciones(List<Funcion> f){
		this.funciones=f;
	}
	
	public List<Funcion> getFunciones(){
		return this.funciones;
	}
	
	public void setModelo(Modelo modelo){
		this.modelo=modelo;
	}
	
	public Modelo getModelo(){
		return this.modelo;
	}
	
	public void valueChanged(ListSelectionEvent arg0) {
		if (!this.getModelo().getFunciones().isEmpty()){
		this.getFunciones().clear();
		VistaLista vistaLista=(VistaLista)arg0.getSource();
		int []vector=vistaLista.getSelectedIndices();
		for (int i=0;i<vector.length;i++)
		this.getFunciones().add((Funcion)this.getModelo().getFunciones().get(vector[i]));
		}
		this.repaint();
	}
}
